package diva.pap;

import static diva.lib.lang.Lang.MINUTE;
import static diva.lib.lang.Lang.schedule;
import static diva.lib.lang.Lang.set;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import diva.android_library.ActivityPresenter;
import diva.lib.event.Event;
import diva.lib.event.Listener;
import diva.lib.lang.Lang.Work;
import diva.lib.lang.Run;
import diva.pap.model.Application;

public abstract class SellNotificationPresenter extends ActivityPresenter {
  private final Run sendNotificationRequest = new Run() {
    public void run() {
      SellNotificationRequest<?> request = createNotificationRequest();
      if (set(lastTime)) request.setFromTime(lastTime);
      request.send();
    }
  };

  private Work notificationWork;
  private String lastTime;

  public SellNotificationPresenter(Activity activity) {
    super(activity);
  }

  public void onCreate() {
    sendNotificationRequest.run();
    notificationWork = schedule(5 * MINUTE, sendNotificationRequest);
    notificationWork.start();

    attach(Application.getInstance().getEventReload(), new Listener<Void>() {
      public void onEvent(Event<Void> event, Void arg) {
        sendNotificationRequest.run();
      }
    });
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    notificationWork.stop();
  }

  protected abstract SellNotificationRequest<?> createNotificationRequest();

  protected void onNotificationRequestDone(SellNotificationRequest<?> request) {
    lastTime = request.getTime();
  }

  protected void showSellNotification(String title, String text) {
    NotificationManager manager =
        (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification =
        new Notification(R.drawable.ic_notification_logo, title, System.currentTimeMillis());
    // notification.defaults |= Notification.DEFAULT_SOUND;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    // notification.defaults |= Notification.DEFAULT_VIBRATE;

    Intent toLaunch = new Intent(activity, LoginActivity.class);
    toLaunch.setAction(Intent.ACTION_MAIN);
    toLaunch.addCategory(Intent.CATEGORY_LAUNCHER);
    // ComponentName componentName = new ComponentName(activity, LoginActivity.class);
    // intent.setComponent(componentName);
    // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(activity, 0, toLaunch, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(activity.getApplicationContext(), title, text, pendingIntent);
    manager.notify(notification.hashCode(), notification);
  }

}
